<template>
  <view>
    <!-- 骨架屏 -->
    <tui-skeleton v-if="skeletonShow" :isLoading="false" backgroundColor="#fafafa" borderRadius="10rpx"></tui-skeleton>
    <view class="container tui-skeleton">
      <!--header-->
      <view class="tui-header-box" :style="{ height: height + 'px', background: 'rgba(255,255,255,' + opcity + ')' }">
        <view class="tui-header" :style="{ paddingTop: top + 'px', opacity: opcity }">商品详情</view>
        <view class="tui-header-icon" :style="{ marginTop: (top + (height - top - 30) / 2) + 'px' }">
          <view class="tui-icon-box" :style="{ backgroundColor: 'rgba(0, 0, 0,' + iconOpcity + ')' }" @tap="back">
            <tui-icon name="arrowleft" :size="30" :color="opcity >= 1 ? '#000' : '#fff'"></tui-icon>
          </view>
          <!-- <view class="tui-icon-box tui-icon-ml" :style="{backgroundColor: 'rgba(0, 0, 0,' + iconOpcity + ')'}" @tap.stop="openMenu">
                        <tui-icon name="more-fill" :size="20" :color="opcity >= 1 ? '#000' : '#fff'"></tui-icon>
                        <tui-badge type="red" :scaleRatio="0.8" absolute top="0" right="-4rpx">5</tui-badge>
                    </view> -->
        </view>
      </view>
      <!--header-->

      <!--banner-->
      <view class="tui-banner-swiper">
        <swiper :autoplay="true" :interval="5000" :duration="150" :circular="true" :style="{ height: scrollH + 'px' }" @change="bannerChange">
          <block v-for="(item, index) in banner" :key="index">
            <swiper-item :data-index="index" @tap.stop="previewImage">
              <image :src="item.picUrl" class="tui-slide-image tui-skeleton-rect" :style="{ height: scrollH + 'px' }" />
            </swiper-item>
          </block>
        </swiper>
        <view class="tui-banner-tag">
          <tui-tag padding="12rpx 18rpx" type="translucent" shape="circleLeft" :scaleMultiple="0.82" originRight>{{ bannerIndex + 1 }}/{{ banner.length }}</tui-tag>
        </view>
      </view>

      <!--banner-->

      <view class="tui-pro-detail">
        <!-- 标题 -->
        <view class="tui-product-title tui-border-radius">
          <view class="tui-pro-pricebox tui-padding">
            <view class="tui-pro-price">
              <view>
                <text>￥</text>
                <text class="tui-price">{{ GoodsDetail.soldPrice }}</text>
              </view>
              <tui-tag padding="10rpx 20rpx" size="24rpx" plain type="high-green" shape="circle" :scaleMultiple="0.8">新品</tui-tag>
            </view>
            <!--                        <view class="tui-collection tui-size" @tap="collecting">
                            <tui-icon :name="collected ? 'like-fill' : 'like'" :color="collected ? '#ff201f' : '#333'" :size="20"></tui-icon>
                            <view class="tui-scale-collection tui-skeleton-circular" :class="{'tui-icon-red':collected}">收藏</view>
                        </view> -->
          </view>
          <view class="tui-original-price tui-gray">
            价格
            <text class="tui-line-through tui-skeleton-rect">￥{{ GoodsDetail.price }}</text>
          </view>
          <view class="tui-pro-titbox">
            <view class="tui-pro-title tui-skeleton-fillet">{{ GoodsDetail.productName }}</view>
            <button open-type="share" class="tui-share-btn tui-share-position">
              <tui-tag type="gray" shape="circleLeft" padding="12rpx 16rpx">
                <view class="tui-share-box">
                  <tui-icon name="partake" color="#999" :size="15"></tui-icon>
                  <text class="tui-share-text tui-gray tui-size">分享</text>
                </view>
              </tui-tag>
            </button>
          </view>
          <view class="tui-padding">
            <view class="tui-sub-title tui-size tui-gray">机不可失，时不再来，赶快下单购买吧</view>
            <view class="tui-sale-info tui-size tui-gray">
              <!-- <view class="tui-skeleton-fillet">快递：0.00</view> -->
              <view class="tui-skeleton-fillet">销量{{ GoodsDetail.soldStock || 0 }}</view>
              <!-- <view class="tui-skeleton-fillet">浙江杭州</view> -->
            </view>
          </view>
        </view>

        <!-- 优惠与已选商品 -->
        <view class="tui-basic-info tui-mtop tui-radius-all">
          <view class="tui-list-cell" @tap="triggerCouponPicker(true)" v-if="couponData.length && enableCoupon">
            <view class="tui-bold tui-cell-title tui-skeleton-rect">优惠</view>
            <view class="tui-selected-box tui-skeleton-rect">领取优惠券</view>
            <view class="tui-ml-auto tui-skeleton-rect">
              <tui-icon name="more-fill" :size="20" color="#666"></tui-icon>
            </view>
          </view>
          <view class="tui-list-cell" @tap="showPopup">
            <view class="tui-bold tui-cell-title tui-skeleton-rect">已选</view>
            <view class="tui-selected-box tui-skeleton-rect">{{ subProData ? subProData.title : '请选择规格' }}</view>
            <view class="tui-ml-auto tui-skeleton-rect">
              <tui-icon name="more-fill" :size="20" color="#666"></tui-icon>
            </view>
          </view>
          <!--                    <view class="tui-list-cell" @tap="showPopup">
                        <view class="tui-bold tui-cell-title tui-skeleton-rect">送至</view>
                        <view class="tui-addr-box">
                            <view class="tui-addr-item tui-skeleton-rect">北京朝阳区三环到四环之间</view>
                            <view class="tui-addr-item tui-skeleton-rect">今日23:59前完成下单，预计6月28日23:30前发货，7月1日24:00前送达</view>
                        </view>
                        <view class="tui-right">
                            <tui-icon name="more-fill" :size="20" color="#666"></tui-icon>
                        </view>
                    </view> -->
          <view class="tui-list-cell tui-skeleton-rect tui-last">
            <view class="tui-bold tui-cell-title tui-skeleton-rect">运费</view>
            <view class="tui-selected-box tui-skeleton-rect">在线支付免运费</view>
          </view>

          <view class="tui-guarantee" v-if="false">
            <view class="tui-guarantee-item">
              <tui-icon name="circle-selected" :size="14" color="#999"></tui-icon>
              <text class="tui-pl tui-skeleton-rect">可配送海外</text>
            </view>
            <view class="tui-guarantee-item">
              <tui-icon name="circle-selected" :size="14" color="#999"></tui-icon>
              <text class="tui-pl tui-skeleton-rect">店铺发货&售后</text>
            </view>
            <view class="tui-guarantee-item">
              <tui-icon name="circle-selected" :size="14" color="#999"></tui-icon>
              <text class="tui-pl tui-skeleton-rect">7天无理由退货</text>
            </view>
            <view class="tui-guarantee-item">
              <tui-icon name="circle-selected" :size="14" color="#999"></tui-icon>
              <text class="tui-pl tui-skeleton-rect">闪电退款</text>
            </view>
            <view class="tui-guarantee-item">
              <tui-icon name="circle-selected" :size="14" color="#999"></tui-icon>
              <text class="tui-pl tui-skeleton-rect">极速审核</text>
            </view>
          </view>
        </view>

        <!-- 扩展属性 -->
        <view v-if="GoodsDetail.extendsProperties && GoodsDetail.extendsProperties.length>0" class="tui-cmt-box tui-mtop tui-radius-all tui-skeleton-rect">
          <view v-for="(item, index) in GoodsDetail.extendsProperties" :key="index" :class="index!=GoodsDetail.extendsProperties.length-1?'tui-list-cell tui-skeleton-rect': 'tui-list-cell tui-skeleton-rect tui-last'">
            <view class="tui-bold tui-cell-title tui-skeleton-rect">{{Object.keys(item)[0]}}</view>
            <view class="tui-selected-box tui-skeleton-rect">{{Object.values(item)[0]}}</view>
          </view>
        </view>

        <!-- 评论 -->
        <view v-if="userRatings.customerId" class="tui-cmt-box tui-mtop tui-radius-all tui-skeleton-rect">
          <view class="tui-list-cell tui-last tui-between">
            <view class="tui-bold tui-cell-title">评价</view>
            <view class="tui-flex-center" @tap="common">
              <text class="tui-cmt-all">查看全部</text>
              <tui-icon name="more-fill" :size="20" color="#ff201f"></tui-icon>
            </view>
          </view>

          <view class="tui-cmt-content tui-padding">
            <view class="tui-cmt-user">
              <image :src="userRatings.avatarUrl" class="tui-acatar"></image>
              <view>{{ userRatings.customerNickName }}</view>
            </view>
            <view class="tui-cmt">{{ userRatings.comment }}</view>
            <!-- <view class="tui-attr">颜色：叠层钛钢流苏耳环（A74）</view> -->
          </view>

          <view class="tui-cmt-btn">
            <tui-button width="240rpx" height="64rpx" :size="24" type="black" plain shape="circle" @click="common">查看全部评价</tui-button>
          </view>
        </view>
        <view v-else style="text-align: center;color: #999999;" class="tui-mtop tui-radius-all tui-skeleton-rect">
          该商品暂无评论
        </view>

        <!-- 详情 -->
        <view class="tui-nomore-box">
          <tui-nomore text="宝贝详情" backgroundColor="#f7f7f7"></tui-nomore>
        </view>
        <!-- 这里宝贝详情后台用的富文本 -->
        <view class="tui-product-img tui-radius-all">
          <rich-text class="product-detail-container" :nodes="GoodsDetail.detailDesc"></rich-text>
          <!-- <image :src="'https://www.thorui.cn/img/detail/' + (index + 1) + '.jpg'" v-for="(img, index) in 20" :key="index"
                    mode="widthFix"></image> -->
        </view>
        <tui-nomore text="已经到最底了" backgroundColor="#f7f7f7"></tui-nomore>
        <view class="tui-safearea-bottom"></view>
      </view>

      <!--底部操作栏-->
      <view class="tui-operation">
        <view class="tui-operation-left tui-col-5">
          <view class="tui-operation-item" @click="toHome" hover-class="tui-opcity" :hover-stay-time="150">
            <tui-icon name="home" :size="22" color="#333"></tui-icon>
            <view class="tui-operation-text tui-scale-small">首页</view>
          </view>
          <button open-type="contact" :session-from="merchantId">
            <view class="tui-operation-item" hover-class="tui-opcity" :hover-stay-time="150">
              <tui-icon name="kefu" :size="22" color="#333"></tui-icon>
              <view class="tui-operation-text tui-scale-small">客服</view>
            </view>
          </button>
          <view class="tui-operation-item" @click="toCart" hover-class="tui-opcity" :hover-stay-time="150">
            <tui-icon name="cart" :size="22" color="#333"></tui-icon>
            <view class="tui-operation-text tui-scale-small">购物车</view>
            <!-- <tui-badge type="red" absolute :scaleRatio="0.8" right="10rpx" top="-4rpx">9</tui-badge> -->
          </view>
        </view>
        <view class="tui-operation-right tui-right-flex tui-col-7 tui-btnbox-4">
          <view class="tui-flex-1">
            <tui-button height="68rpx" :size="26" type="danger" shape="circle" @tap="addCart">加入购物车</tui-button>
          </view>
          <view class="tui-flex-1">
            <tui-button height="68rpx" :size="26" type="warning" shape="circle" @tap="doPay">立即购买</tui-button>
          </view>
        </view>
      </view>

      <!--底部操作栏--->

      <!--顶部下拉菜单-->
      <tui-top-dropdown backgroundColor="rgba(76, 76, 76, 0.95)" :show="menuShow" :height="0" @close="closeMenu">
        <view class="tui-menu-box tui-padding tui-ptop">
          <view class="tui-menu-header" :style="{ paddingTop: top + 'px' }">功能直达</view>
          <view class="tui-menu-itembox">
            <block v-for="(item, index) in topMenu" :key="index">
              <view class="tui-menu-item" hover-class="tui-opcity" :hover-stay-time="150" @tap="btnTopMenu(index)">
                <view class="tui-badge-box">
                  <tui-icon :name="item.icon" color="#fff" :size="item.size"></tui-icon>
                  <tui-badge type="red" :scaleRatio="0.8" absolute right="-8rpx" v-if="item.badge">{{ item.badge }}</tui-badge>
                </view>
                <view class="tui-menu-text">{{ item.text }}</view>
              </view>
            </block>
          </view>
          <view class="tui-icon-up_box">
            <tui-icon name="up" color="#fff" :size="26" @click="closeMenu"></tui-icon>
          </view>
        </view>
      </tui-top-dropdown>
      <!---顶部下拉菜单-->

      <!--底部选择层-->
      <tui-bottom-popup :show="popupShow" @close="hidePopup">
        <view class="tui-popup-box">
          <!--sku title部分-->
          <view class="tui-product-box tui-padding">
            <image :src="GoodsDetail.pic" class="tui-popup-img"></image>
            <view class="tui-popup-content">
              <view class="tui-popup-title">
                {{ productInfo.title }}
              </view>
              <view class="tui-popup-price">
                <view class="tui-amount tui-bold">￥{{ productInfo.price }}</view>
                <view class="tui-number">编号: {{ GoodsDetail.productCode }}</view>
              </view>
            </view>
          </view>
          <scroll-view scroll-y class="tui-popup-scroll">
            <view class="tui-scrollview-box">
              <view v-for="(row,i) in skuData" :key="i">
                <view class="tui-bold tui-attr-title">{{ row.specificationName }}</view>
                <view class="tui-attr-box">
                  <view v-for="(item, index) in row.productSpecPropertyDTOS" :key="item.speciPropertyId" @tap="setSelectSpec(item, row.specificationId)" :class="{'tui-attr-active' : item.active, 'tui-attr-disable': !item.canSelect}" class="tui-attr-item">{{ item.propertyName }}</view>
                </view>
              </view>
              <!-- <view class="tui-bold tui-attr-title">尺寸</view>
                            <view class="tui-attr-box">
                                <view class="tui-attr-item">5cm</view>
                                <view class="tui-attr-item">8cm</view>
                                <view class="tui-attr-item">12cm</view>
                                <view class="tui-attr-item">16cm</view>
                                <view class="tui-attr-item tui-attr-active">18cm</view>
                            </view> -->

              <!-- <view class="tui-bold tui-attr-title">保障服务</view>
                            <view class="tui-attr-box">
                                <view class="tui-attr-item">半年掉钻保 ￥4.0</view>
                            </view>

                            <view class="tui-bold tui-attr-title">只换不修</view>
                            <view class="tui-attr-box">
                                <view class="tui-attr-item">三月意外换￥2.0</view>
                                <view class="tui-attr-item">半年意外换￥2.0</view>
                            </view> -->

              <view class="tui-number-box tui-bold tui-attr-title">
                <view class="tui-attr-title">数量</view>
                <tui-numberbox :max="99" :min="1" :value="number" @change="change"></tui-numberbox>
              </view>
            </view>
          </scroll-view>
          <view class="tui-operation tui-operation-right tui-right-flex tui-popup-btn">
            <view class="tui-flex-1">
              <tui-button height="72rpx" :size="28" type="danger" shape="circle" @click="cartList">加入购物车</tui-button>
            </view>
            <view class="tui-flex-1">
              <tui-button height="72rpx" :size="28" type="warning" shape="circle" @click="handleBuyGoods">立即购买</tui-button>
            </view>
          </view>
          <view class="tui-right">
            <tui-icon name="close-fill" color="#999" :size="20" @click="hidePopup"></tui-icon>
          </view>
        </view>
      </tui-bottom-popup>
      <coupon-picker :show="showCouponPicker" :valid="false" :coupons="couponData" @close='triggerCouponPicker' @refresh="GetCoupons"></coupon-picker>
      <!--底部选择层-->
    </view>
  </view>
</template>

<script>
import config from "../../config/index.js";
import CouponPicker from "@/components/views/t-coupon-picker/t-coupon-picker.vue";
export default {
  components: { CouponPicker },
  data() {
    return {
      skeletonShow: true,
      height: 64, //header高度
      top: 26, //标题图标距离顶部距离
      scrollH: 0, //滚动总高度
      opcity: 0,
      iconOpcity: 0.5,
      banner: [],
      bannerIndex: 0,
      topMenu: [
        {
          icon: "message",
          text: "消息",
          size: 26,
          badge: 3,
        },
        {
          icon: "home",
          text: "首页",
          size: 23,
          badge: 0,
        },
        {
          icon: "people",
          text: "我的",
          size: 26,
          badge: 0,
        },
        {
          icon: "cart",
          text: "购物车",
          size: 23,
        },
        {
          icon: "kefu",
          text: "客服小蜜",
          size: 26,
          badge: 0,
        },
        {
          icon: "feedback",
          text: "我要反馈",
          size: 23,
          badge: 0,
        },
        {
          icon: "share",
          text: "分享",
          size: 26,
          badge: 0,
        },
      ],
      menuShow: false,
      popupShow: false,
      collected: false,
      productCode: "", // 商品id
      GoodsDetail: {}, // 商品的信息
      number: 1, // 选择购买的商品
      // selectSpec: '请选择规格',     // 已经选择的规格，这个要展示出来
      userRatings: {}, // 用户评论
      merchantId: config.merchantId,
      couponData: [],
      showCouponPicker: false,
      activeSKU: [],
    };
  },
  onLoad: function (options) {
    let obj = {};
    // #ifdef MP-WEIXIN
    obj = wx.getMenuButtonBoundingClientRect();
    // #endif
    // #ifdef MP-BAIDU
    obj = swan.getMenuButtonBoundingClientRect();
    // #endif
    // #ifdef MP-ALIPAY
    my.hideAddToDesktopMenu();
    // #endif

    const { systemInfo: res } = this.$store.state;
    this.width = obj.left || res.windowWidth;
    this.height = obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44;
    this.top = obj.top
      ? obj.top + (obj.height - 32) / 2
      : res.statusBarHeight + 6;
    this.scrollH = res.windowWidth;
    this.productCode = options.productCode;
    this.init();
  },
  methods: {
    async init() {
		uni.showShareMenu({
			// withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		})
		await this.GetProductDetail();
		this.$config.couponEnable && this.GetCoupons();
		this.GetCommentList();
		setTimeout(() => {
			this.skeletonShow = false;
		}, 500);
    },
    async GetCommentList() {
      const { productCode } = this.$data;
      let { data } = await this.$api.GetCommentList({
		  productId: productCode,
		  pageNum: 1
	  });
      if (Array.isArray(data) && data.length != 0) {
        this.userRatings = data[0];
      }
    },
    // 根据产品编码查询产品详细
    async GetProductDetail() {
      const { productCode } = this.$data;
      let { data } = await this.$api.GetProductDetail(productCode);
      data.detailDesc = data.detailDesc.replace(
        /\<img/gi,
        '<img style="max-width: 100%; display:block; margin:0 auto; vertical-align: top;"'
      );
      this.GoodsDetail = data;

      // console.log(data.specDTOS,"data.specDTOS")

      // 加载轮播图
      let swiperList =
        Array.isArray(data.pics) &&
        data.pics.filter((item) => item.picFun == 1);
      this.banner = swiperList;

      // 默认选中一个SKU
      this.initSKU();
    },
    initSKU() {
      const { productItemDTOs } = this.GoodsDetail;
      if (productItemDTOs && productItemDTOs.length) {
        this.activeSKU = productItemDTOs[0].productItemSpecDTOS?.map((d) => ({
          propertyName: d.propertyName,
          speciPropertyId: d.speciPropertyId,
          specificationId: d.specificationId,
        }));
      }
    },
    async GetCoupons() {
      const { data } = await this.$api.GetCouponsByProduct(
        this.productCode,
        this.$config.merchantId,
        this.$store.state.customerId
      );
      // console.log(data, 'couponsss')
      this.couponData = data;
    },
    //选择规格的函数
    setSelectSpec(spec, rowid) {
      if (spec.canSelect) {
        const index = this.activeSKU.findIndex((d) => {
          return (
            d.speciPropertyId === spec.speciPropertyId &&
            d.specificationId === rowid
          );
        });
        if (index < 0) {
          const rowIndex = this.activeSKU.findIndex(
            (d) => d.specificationId === rowid
          );
          rowIndex >= 0 && this.activeSKU.splice(rowIndex, 1);
          this.activeSKU.push({
            propertyName: spec.propertyName,
            speciPropertyId: spec.speciPropertyId,
            specificationId: rowid,
          });
        } else {
          this.activeSKU.splice(index, 1);
        }
      }
    },
    // 加入购物车
    addCart() {
	  this.$store.dispatch("USER_LOGIN", {
		  desc: '用于登录时记录您的必要身份信息',
		  callBack: this.showPopup
	  })
    },
    doPay() {
      this.addCart();
    },

    async cartList() {
      const { productCode, number, GoodsDetail } = this.$data;
      const { success, unSelect, product } = this.getSubProduct();

      if (success) {
        const result = await this.$api.SetCartList({
          num: number,
          productId: product.productId,
          productItemId: product.id,
          customerId: this.$store.state.customerId,
          type: 1,
        });
        uni.showToast({ title: "已加入购物车" });
        this.hidePopup();
      } else {
        uni.showToast({
          icon: "none",
          title: `请选择${unSelect[0]?.specificationName}`,
        });
      }
      // 统计用户获取的规格 然后汇总下数据
      // let productSpeci = []
      // let { specDTOS } = GoodsDetail
      // Array.isArray(specDTOS) && specDTOS.forEach(item=>{
      //     const { selected } = item
      //     let { id } = item.properties[selected]
      //     productSpeci.push(id)
      // })
      // let result = await this.$api.SetCartList({
      //     num: number,
      //     productId: productCode,
      //     productSpecis: productSpeci.toString()
      // })
      // uni.showToast({title: "已加入购物车"})
      // this.hidePopup()
    },
    // 创建订单
    async handleBuyGoods() {
      // this.popupShow = false

      let { number, GoodsDetail } = this.$data;
      const { success, unSelect, product } = this.getSubProduct();

      if (!success) {
        uni.showToast({
          icon: "none",
          title: `请选择${unSelect[0].specificationName}`,
        });
        return;
      }

      GoodsDetail = JSON.parse(JSON.stringify(GoodsDetail));
      // 商品名称
      GoodsDetail.productName = this.productInfo.title;
      // GoodsDetail.properties = GoodsDetail.specDTOS
      // 商品件数
      GoodsDetail.productNum = number;
      // 价格
      GoodsDetail.price = this.productInfo.price;
      // 子商品信息
      GoodsDetail.subProduct = this.getSubProduct().product;

      let { productCode } = GoodsDetail;
      // 已经选择的规格id
      // let specPropertyIds = []

      // Array.isArray(properties) && properties.map(row=>{
      //     let { properties, selected } = row
      //     const id = properties[selected].id
      //     specPropertyIds.push(id)
      // })
      // GoodsDetail.specPropertyIds = specPropertyIds

      this.$store.dispatch("ADD_BUYLIST", [GoodsDetail]);

      this.hidePopup();

      uni.navigateTo({
        url: `/pagesB/submitOrder/submitOrder?productCode=${productCode}`,
      });
    },
    bannerChange: function (e) {
      this.bannerIndex = e.detail.current;
    },
    previewImage: function (e) {
      let index = e.currentTarget.dataset.index;
      uni.previewImage({
        current: this.banner[index],
        urls: this.banner,
      });
    },
    back: function () {
		const pages = getCurrentPages()
		if (pages.length > 1) {
			uni.navigateBack()
		} else {
			this.HANDLE_JUMP_HOME()
		}
    },
    openMenu: function () {
      this.menuShow = true;
    },
    closeMenu: function () {
      this.menuShow = false;
    },
    showPopup: function () {
      this.popupShow = true;
    },
    hidePopup: function () {
      this.popupShow = false;
    },
    change: function (e) {
      this.number = e.value;
    },
    async collecting() {
      const { collected, GoodsDetail } = this.$data;
      // console.log(this.$util)
      if (!collected) {
        try {
          await this.$util.addCollectList(GoodsDetail);
        } catch (err) {
          uni.showToast({ title: "请勿重复添加" });
          return;
        }
        this.collected = true;
      } else {
        this.$util.removeCollectList(GoodsDetail);
        this.collected = false;
      }
    },
    common: function () {
      // this.tui.toast('功能开发中~');
      uni.navigateTo({
        url: `/pagesB/ratings/ratings?productCode=${this.productCode}`,
      });
    },
    btnTopMenu(index) {
      this.closeMenu();
      if (index == 4) {
        uni.makePhoneCall({
          phoneNumber: "10086",
        });
      } else if (index == 6) {
        // #ifdef MP
        this.common();
        // #endif

        // #ifndef MP
        this.onShare();
        // #endif
      } else {
        let url = {
          0: "pagesB/message/message",
          1: "../mall/mall",
          2: "../my/my",
          3: "../shopcart/shopcart",
          5: "/pages/my/feedback/feedback?page=mall",
        }[index];
        url && this.tui.href(url);
      }
    },
    coupon() {
      uni.navigateTo({
        url: "pagesB/coupon/coupon",
      });
    },
    onShare() {
      //#ifdef APP-PLUS
      plus.share.sendWithSystem(
        {
          content: "ThorUI商城模板",
          href: "https://www.thorui.cn/",
        },
        function () {
          console.log("分享成功");
        },
        function (e) {
          console.log("分享失败：" + JSON.stringify(e));
        }
      );
      //#endif
    },
    toCart() {
      console.log("前往购物车");
      uni.switchTab({
        url: "/pages/shopcart/shopcart",
      });
    },
    toHome() {
      uni.switchTab({
        url: "/pages/mall/mall",
      });
    },
    triggerCouponPicker(show = false) {
      this.showCouponPicker = show;
    },
    // 指定的 属性值在当前选中状态下, 是否还可以被选则
    skuVierfy(item, rowId) {
      const { productItemDTOs = [] } = this.GoodsDetail;

      // 完全没有选中项, 这个item肯定可以选
      if (!this.activeSKU.length) {
        return true;
      } else {
        // 除了item所在行, 还有没有被选中的
        const otherActive = this.activeSKU.filter(
          (d) => d.specificationId !== rowId
        );
        // 如果其他行都没有被选中, 那么 这个item 肯定可以选
        if (!otherActive.length) {
          return true;
        } else {
          // 如果其他行有被选中的, 那么找 在选中的基础上 有没有和item匹配的项(子商品)
          const matched = productItemDTOs.find((d) => {
            let ret = true;
            // 匹配已经选中的
            otherActive.forEach((sku) => {
              const found = d.productItemSpecDTOS.find((dd) => {
                return (
                  dd.specificationId === sku.specificationId &&
                  dd.speciPropertyId === sku.speciPropertyId
                );
              });
              ret &= !!found;
            });
            // 当前被验证的项
            ret &= !!d.productItemSpecDTOS.find((dd) => {
              return (
                dd.specificationId === rowId &&
                dd.speciPropertyId === item.speciPropertyId
              );
            });

            return ret;
          });

          return matched;
        }
      }
    },
    // 根据已经选中sku, 找到具体的子商品
    getSubProduct() {
      const {
        productItemDTOs = productItemDTOs || [],
        productSpecDTOS = productSpecDTOS || [],
      } = this.GoodsDetail;
      // 没有规格的情况
      if (
        productItemDTOs.length === 1 &&
        !productItemDTOs[0].productItemSpecDTOS
      ) {
        return {
          success: true,
          product: productItemDTOs[0],
        };
      }
      // 是不是每个规格都有被选
      if (productSpecDTOS.length === this.activeSKU?.length) {
        const matched = productItemDTOs.find((d) => {
          let ret = true;
          // 匹配已经选中的
          this.activeSKU.forEach((sku) => {
            const found = d.productItemSpecDTOS.find((dd) => {
              return (
                dd.specificationId === sku.specificationId &&
                dd.speciPropertyId === sku.speciPropertyId
              );
            });
            ret &= !!found;
          });

          return ret;
        });
        return {
          success: true,
          product: matched,
        };
      } else {
        const unSelect = productSpecDTOS.filter((d) => {
          return !this.activeSKU.find(
            (dd) => dd.specificationId === d.specificationId
          );
        });
        return {
          success: false,
          unSelect,
        };
      }
    },
  },
  onPageScroll(e) {
    let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop;
    let opcity = scroll / this.scrollH;
    if (this.opcity >= 1 && opcity >= 1) {
      return;
    }
    this.opcity = opcity;
    this.iconOpcity = 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity);
  },
  onShareAppMessage(obj) {
  	return {
  		title: this.productInfo.title,
		path: `/pagesB/productDetail/productDetail?productCode=${this.productCode}`,
  		// 自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4。
  		imageUrl: this.productInfo.pic
  	}
  },
  computed: {
    // 这个是检测用户有没有选规格
    selectSpecFlag() {
      let specDTOS = this.GoodsDetail.specDTOS;
      let flag = false;
      flag =
        Array.isArray(specDTOS) &&
        specDTOS.every((item) => item.selected || item.selected == 0);
      return flag;
    },
    enableCoupon() {
      return this.$config.couponEnable;
    },
    // 根据已经选择的 sku子项, 输出sku数据
    skuData() {
      const { productSpecDTOS = [] } = this.GoodsDetail;
      const ret = [];
      if (productSpecDTOS.length) {
        // 遍历规格 (如: 颜色)
        productSpecDTOS.forEach((row) => {
          const tmpRow = {
            specificationId: row.specificationId,
            specificationName: row.specificationName,
            productSpecPropertyDTOS: [],
          };
          // 遍历规格中的每一项 (如: 红色)
          row.productSpecPropertyDTOS.forEach((item) => {
            // 这一项有没有被选中的
            const found = this.activeSKU.find((d) => {
              return (
                d.speciPropertyId === item.speciPropertyId &&
                d.specificationId === row.specificationId
              );
            });
            // 选中状态
            const tmpItem = {
              ...item,
              active: found,
              canSelect: this.skuVierfy(item, row.specificationId),
            };
            // 此项是否可以操作(在当前已经选择的前提下)
            tmpRow.productSpecPropertyDTOS.push(tmpItem);
          });
          ret.push(tmpRow);
        });
      }
      return ret;
    },
    // 被选中的子商品
    subProData() {
      return this.getSubProduct().product;
    },
    // sku面板中的商品信息 (没有选中的sku用主商品, 否则用子商品)
    productInfo() {
      const { productName, price } = this.GoodsDetail;
      const ret = {
        title: productName,
        price,
      };
      const sub = this.getSubProduct();

      if (sub.success && sub.product) {
        ret.title = sub.product.title;
        ret.price = sub.product.price;
      }
      return ret;
    },
  },
  watch: {
	  subProData(val) {
		  const { title: t, price } = this.productInfo
		  const title = `【仅¥${price}】${t}`
		  const { pic } = this.GoodsDetail
		  const path = `/pagesB/productDetail/productDetail?productCode=${this.productCode}`

		  this.shareOpts = {
			title,
			imageUrl: pic,
			path
		  }
	  }
  }
};
</script>

<style lang="scss">
@import "./productDetail.scss";
page {
  background-color: #f7f7f7;
}
</style>
